package com.nullpointer.xchat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nullpointer.xchat.fragment.LicenseDialogFragment;
import com.nullpointer.xchat.fragment.LicenseDialogFragment.OnLicenseDialogFragment;
import com.nullpointer.xchat.object.UserInfo.GenderType;
import com.nullpointer.xchat.service.ChatService;
import com.nullpointer.xchat.utils.Common;
import com.nullpointer.xchat.utils.DataManager;
import com.nullpointer.xchat.utils.KiraGameLog;
import com.nullpointer.xchat.utils.Utils;

public class SplashActivity extends SherlockFragmentActivity {

	private ImageView ivAvatar;
	private EditText etName;
	private TextView tvMale;
	private TextView tvFemale;
	private TextView tvOther;
	private TextView tvRoom;
	private Spinner snRoom;
	private Button btJoinchat;
	private LinearLayout llNotice;
	private ProgressBar pbLoading;
	private TextView tvNotice;
	private View vSplit;
	private TextView tvAction;
	private LinearLayout llLogin;

	// Animation
	private Animation animationShow;
	private Animation animationHide;

	private GenderType gender = GenderType.FEMALE;
	private int focus = Color.parseColor("#ff8800");
	private int normal = Color.parseColor("#333333");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);
		KiraGameLog.d("-------SplashActivity onCreate-------");
		findViewIds();
		setEvent();
		init();
	}

	private void setEvent() {
		tvFemale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tvFemale.setTextColor(focus);
				tvMale.setTextColor(normal);
				tvOther.setTextColor(normal);
				gender = GenderType.FEMALE;
			}
		});
		tvMale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tvFemale.setTextColor(normal);
				tvMale.setTextColor(focus);
				tvOther.setTextColor(normal);
				gender = GenderType.MALE;
			}
		});
		tvOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tvFemale.setTextColor(normal);
				tvMale.setTextColor(normal);
				tvOther.setTextColor(focus);
				gender = GenderType.ANY;
			}
		});
		btJoinchat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(SplashActivity.this, etName);
				showLicenseDialog();
			}
		});

		etName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etName.getText() != null
						&& etName.getText().toString().trim().length() >= 3) {

					if (Utils.checkBadword(etName.getText().toString())) {
						showNotice(false, "Please don't use sexual content!",
								null);
						btJoinchat.setEnabled(false);
					} else {
						hideNotice();
						btJoinchat.setEnabled(true);
					}
				} else {
					showNotice(false,
							"Your name must be at least 3 characters long!",
							null);
					btJoinchat.setEnabled(false);
				}
			}
		});
	}

	private void init() {
		animationShow = AnimationUtils.loadAnimation(this,
				R.anim.snackbar_show_animation);
		animationHide = AnimationUtils.loadAnimation(this,
				R.anim.snackbar_hide_animation);

		etName.setText(DataManager.getInstance(this).getUserName());
		if (etName.getText() != null
				&& etName.getText().toString().trim().length() >= 3) {
			hideNotice();
			btJoinchat.setEnabled(true);
		} else {
			showNotice(false, "Your name must be at least 3 characters long!",
					null);
			btJoinchat.setEnabled(false);
		}
		gender = DataManager.getInstance(this).getUserGender();
		if (gender == GenderType.FEMALE) {
			tvFemale.setTextColor(focus);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.MALE) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(focus);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.ANY) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(focus);
		}
		llLogin.setVisibility(View.GONE);
		btJoinchat.setVisibility(View.GONE);

		IntentFilter filter = new IntentFilter(
				ChatService.BROADCAST_NAME_SPLASH);
		LocalBroadcastManager.getInstance(this).registerReceiver(
				changeUIReceiver, filter);

		if (!DataManager.getInstance(this).isLogout()) {
			if ((ChatService.getInstance() == null)
					|| ((ChatService.getInstance() != null) && !ChatService
							.getInstance().isLogin())) {
				startChatService();
			} else {
				startMainUI();
			}
		} else {
			// show Login
			llLogin.setVisibility(View.VISIBLE);
			btJoinchat.setVisibility(View.VISIBLE);
		}
	}

	private void startMainUI() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	private void findViewIds() {
		ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
		etName = (EditText) findViewById(R.id.et_name);
		tvMale = (TextView) findViewById(R.id.tv_male);
		tvFemale = (TextView) findViewById(R.id.tv_female);
		tvOther = (TextView) findViewById(R.id.tv_other);
		tvRoom = (TextView) findViewById(R.id.tv_room);
		snRoom = (Spinner) findViewById(R.id.sn_room);
		btJoinchat = (Button) findViewById(R.id.bt_joinchat);
		llNotice = (LinearLayout) findViewById(R.id.ll_notice);
		pbLoading = (ProgressBar) findViewById(R.id.pbLoading);
		tvNotice = (TextView) findViewById(R.id.tv_notice);
		vSplit = (View) findViewById(R.id.v_split);
		tvAction = (TextView) findViewById(R.id.tv_action);
		llLogin = (LinearLayout) findViewById(R.id.ll_login);
	}

	private void startChatService() {
		stopService(new Intent(this, ChatService.class));
		Intent service = new Intent(this, ChatService.class);
		startService(service);
	}

	private BroadcastReceiver changeUIReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String actionUIMAin = intent
					.getStringExtra(ChatService.CONTROL_ACTION);
			String message = intent.getStringExtra(ChatService.CONTROL_MESSAGE);
			// KiraGameLog.d("get broadcast receive with action " + actionUIMAin
			// + " and message " + message);
			switch (actionUIMAin) {
			case ChatService.SPLASH_ACTION_ON_PRE_SETUP_SERVER:
				onPreSetUpServer();
				break;
			case ChatService.SPLASH_ACTION_ON_FINISHED_SETUP_SERVER:
				onFinishedSetupServer(message);
				break;

			case ChatService.SPLASH_ACTION_NOTIFY_CONNECTION_ONLINE:
				notifyConnectionOnline();
				break;
			case ChatService.SPLASH_ACTION_NOTIFY_CONNECTION_OFFLINE:
				notifyConnectionOffline();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				changeUIReceiver);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.splash, menu);
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		return false;
	}

	private void notifyConnectionOffline() {
		KiraGameLog.d("No Internet connection!");
		showNotice(false, "No Internet Connection!", "WIFI SETTING");
		tvAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
				startActivity(intent);
			}
		});
	}

	private void notifyConnectionOnline() {
		KiraGameLog.d("Internet connection successful!");
		hideNotice();
	}

	private void onPreSetUpServer() {
		showNotice(true, "Connecting to server...", null);
	}

	private void onFinishedSetupServer(String error) {
		hideNotice();
		if (error != null) {
			// ERROR
			showNotice(false, error, "RETRY");
			// setup server fail. re setup?
			tvAction.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					hideNotice();
					setUpServerChat();
				}
			});
		} else {
			startMainUI();
		}

	}

	protected void setUpServerChat() {
		try {
			ChatService.getInstance().setUpServer();
		} catch (NullPointerException e) {
			e.printStackTrace();
			startChatService();
		}
	}

	private void showNotice(boolean isShowProgessbar, String message,
			String action) {
		if (isShowProgessbar) {
			pbLoading.setVisibility(View.VISIBLE);
		} else {
			pbLoading.setVisibility(View.GONE);
		}
		if (message != null) {
			tvNotice.setText(message);
		}
		if (action != null) {
			tvAction.setText(action);
			tvAction.setVisibility(View.VISIBLE);
			vSplit.setVisibility(View.VISIBLE);
		} else {
			tvAction.setVisibility(View.GONE);
			vSplit.setVisibility(View.GONE);
		}

		llNotice.setVisibility(View.VISIBLE);
		llNotice.startAnimation(animationShow);
	}

	private void hideNotice() {
		if (llNotice.getVisibility() == View.GONE) {
			return;
		}
		animationHide.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				llNotice.setVisibility(View.GONE);
			}
		});
		llNotice.startAnimation(animationHide);
	}

	private void showLicenseDialog() {
		try {
			final LicenseDialogFragment dialog = new LicenseDialogFragment();
			dialog.setCancelable(false);
			dialog.setOnExitDialogListener(new OnLicenseDialogFragment() {

				@Override
				public void onCancel() {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAccept() {
					String name = etName.getText().toString();
					if (name == null || name.length() < 3) {
						return;
					}
					DataManager.getInstance(SplashActivity.this).setUserName(
							name);
					DataManager.getInstance(SplashActivity.this).setIsLogout(
							false);
					DataManager.getInstance(SplashActivity.this).setUserGender(
							gender);
					String female = "";
					if (gender == GenderType.FEMALE) {
						female = ". I'm female";
					}
					String status = "Hi! I'm " + name + female
							+ ". Wanna chat with me?";
					DataManager.getInstance(SplashActivity.this).setUserStatus(
							status);
					startChatService();
					llLogin.setVisibility(View.GONE);
					btJoinchat.setVisibility(View.GONE);
				}
			});
			FragmentTransaction transaction = getSupportFragmentManager()
					.beginTransaction();
			transaction.add(dialog, "LicenseDialogFragment");
			transaction.commitAllowingStateLoss();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
